import numpy, os

def mnist(path):
	Xtrain = load_xfile(path, 'train-images.idx3-ubyte')
	Xtest  = load_xfile(path, 't10k-images.idx3-ubyte')
	Ttrain = load_tfile(path, 'train-labels.idx1-ubyte')
	Ttest  = load_tfile(path, 't10k-labels.idx1-ubyte')
	return Xtrain,Ttrain,Xtest,Ttest

def load_xfile(path, filename):
	return numpy.fromfile(open(full_path(path, filename),'r'),dtype='ubyte',count=16+784*60000)[16:].reshape([60000,784]).astype('float32')/255.0

def load_tfile(path, filename):
	loaded_data = numpy.fromfile(open(full_path(path, filename),'r'),dtype='ubyte',count=8+60000)[8:,numpy.newaxis]
	return numpy.concatenate([loaded_data==t for t in range(10)],axis=1).astype('float32')

def full_path(path, filename):
	return os.path.join(path, filename)
